package com.loveyukari.dao.impl;

import com.loveyukari.dao.IpCoolDao;
import com.loveyukari.model.IpCool;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class JdbcIpCoolDao extends BaseDao implements IpCoolDao {


    private RowMapper<IpCool> ipCoolRowMapper = new RowMapper<IpCool>() {
        @Override
        public IpCool mapRow(ResultSet resultSet, int i) throws SQLException {
            IpCool ipCool = new IpCool();
            ipCool.setIp(resultSet.getString("ip"));
            ipCool.setCity(resultSet.getString("city"));
            ipCool.setDistrict(resultSet.getString("district"));
            ipCool.setProvince(resultSet.getString("province"));
            ipCool.setPointX(resultSet.getString("point_x"));
            ipCool.setPointY(resultSet.getString("point_y"));
            ipCool.setUpdateTime(resultSet.getTimestamp("update_time"));
            return ipCool;
        }
    };
    @Override
    public IpCool select(String ip) {
        String sql = "select * from ip_cool where ip = ?";
        List<IpCool> list = this.getJdbcTemplate().query(sql, ipCoolRowMapper, ip);
        if (list.isEmpty()){
            return null;
        }
        return list.get(0);
    }

    @Override
    public void insert(IpCool ipCool) {
        String sql = "insert into ip_cool (ip,city,district,province,point_x,point_y) values (?,?,?,?,?,?)";
        this.getJdbcTemplate().update(sql,ipCool.getIp(),ipCool.getCity(),ipCool.getDistrict(),ipCool.getProvince(),ipCool.getPointX(),ipCool.getPointY());
    }

    @Override
    public void update(IpCool ipCool) {
        String sql = "update ip_cool set city = ?, district = ?, province = ?, point_x = ?, point_y = ? where ip = ?";
        this.getJdbcTemplate().update(sql,ipCool.getCity(),ipCool.getDistrict(),ipCool.getProvince(),ipCool.getPointX(),ipCool.getPointY(),ipCool.getIp());
    }
}
